# -*- coding: utf-8 -*-
#
# File: PMenuTool.py
#
# Copyright (c) 2007 by Copyright (c) 2007 P2P Informatica LTDA
# Generator: ArchGenXML Version 1.5.2
#            http://plone.org/products/archgenxml
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

__author__ = """Pablo <pablo@p2pinformatica.com>"""
__docformat__ = 'plaintext'

from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import *
from Products.PMenuTool.config import *
from Products.CMFCore.utils import getToolByName

from Products.CMFCore.utils import UniqueObject


##code-section module-header #fill in your manual code here
from StringIO import StringIO
##/code-section module-header

schema = Schema((

    StringField(
        name='OrdenacaoMenu',
        index="FieldIndex",
        required=1,
        widget=SelectionWidget(
            label="Forma de Ordenação do menu",
            format='radio',
            description="",
        ),
        enforce_vocabulary="1",
        vocabulary='getOrdenacaoMenu_vocab'

    ),

    StringField(
        name='TipoOrdenacao',
        index="FieldIndex",
        required=1,
        widget=SelectionWidget(
            label="Tipo de ordenação",
            format='radio',
            description="",
        ),
        enforce_vocabulary="1",
        vocabulary='getTipoOrdenacao_vocab'

    ),

    StringField(
        name='CustomizacaoCSS',
        index="FieldIndex",
        required=1,
        widget=SelectionWidget(
            label="CSS do menu customizado?",
            format='radio',
            description="",
        ),
        enforce_vocabulary="1",
        vocabulary='getCustomizacaoCSS_vocab'

    ),
),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

PMenuTool_schema = OrderedBaseFolderSchema.copy() + \
    schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class PMenuTool(UniqueObject, OrderedBaseFolder):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(UniqueObject,'__implements__',()),) + (getattr(OrderedBaseFolder,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'PMenuTool'

    meta_type = 'PMenuTool'
    portal_type = 'PMenuTool'
    allowed_content_types = ['MenuPrincipal']
    filter_content_types = 1
    global_allow = 0
    content_icon = 'tool_menu.png'
    immediate_view = 'base_view'
    default_view = 'base_view'
    suppl_views = ()
    typeDescription = "PMenuTool"
    typeDescMsgId = 'description_edit_pmenutool'
    toolicon = 'tool_menu.png'


    actions =  (


       {'action': "string:${object_url}/view_menu",
        'category': "object",
        'id': 'view',
        'name': 'view',
        'permissions': ("View",),
        'condition': 'python:1'
       },


    )


    _at_rename_after_creation = True

    schema = PMenuTool_schema

    ##code-section class-header #fill in your manual code here
    aliases = {
                '(Default)'  : 'view_menu',
                'view'       : 'view_menu',
                'index.html' : 'view_menu',
                'edit'       : 'base_edit',
                'properties' : 'base_metadata',
                'sharing'    : 'folder_localrole_form',
                'gethtml'    : '',
                'mkdir'      : '',
    }

    ##/code-section class-header


    # tool-constructors have no id argument, the id is fixed
    def __init__(self, id=None):
        BaseFolder.__init__(self,'tool_menu')
        self.setTitle('PMenuTool')

        ##code-section constructor-footer #fill in your manual code here
        ##/code-section constructor-footer


    # tool should not appear in portal_catalog
    def at_post_edit_script(self):
        self.unindexObject()

        ##code-section post-edit-method-footer #fill in your manual code here
        ##/code-section post-edit-method-footer

    security.declarePublic('getOrdenacaoMenu_vocab')
    def getOrdenacaoMenu_vocab(self):
        vocabulary = (
                        ['sortable_title', 'Ordem alfabética'],
                        ['getObjPositionInParent', 'Posinamento dentro pasta'],
                        ['created', 'Data de criação'],
                        ['modified', 'Data de modificação'],
                        ['id', 'Ordenado pelo id do objeto'],
                     )
        return DisplayList(vocabulary)

    security.declarePublic('getTipoOrdenacao_vocab')
    def getTipoOrdenacao_vocab(self):
        vocabulary = (
                        ['asc', 'Ascendente'],
                        ['des', 'Descendente'],
                     )
        return DisplayList(vocabulary)

    security.declarePublic('getCustomizacaoCSS_vocab')
    def getCustomizacaoCSS_vocab(self):
        vocabulary = (
                        ['True', 'Sim'],
                        ['False', 'Não'],
                     )
        return DisplayList(vocabulary)

    security.declarePublic('setCSSPMenu')
    def setCustomizacaoCSS(self, value):
        portal_css = getToolByName(self, 'portal_css')

        from Products.PMenuTool.config import STYLESHEETS
        # Se usuario marcou a opção Não, tenta registar o css
        #import pdb; pdb.set_trace()
        if 'False' in value:
            try:
                for stylesheet in STYLESHEETS:
                    defaults = {'id': '',
                    'media': 'all',
                    'enabled': True}
                    defaults.update(stylesheet)
                    portal_css.registerStylesheet(**defaults)
            except:
                # No portal_css registry
                pass

        # Se usuario marcou a opção Sim, tenta desregistar o css
        if 'True' in value:
            try:
                for stylesheet in STYLESHEETS:
                    portal_css.unregisterResource(stylesheet['id'])
            except:
                # No portal_css registry
                pass

        # Salva o field
        self.Schema()['CustomizacaoCSS'].set(self, value)



    def processaMenu(self):
        portal_url = self.portal_url()
        try:
            user_logado = self.portal_membership.getAuthenticatedMember()
            if user_logado:
                grupos = user_logado.getGroups()
            else:
                grupos = []
        except:
            grupos = []
        #import pdb; pdb.set_trace()
        try:
            out = StringIO()
            contentFilter = {}
            contentFilter["sort_on"] = self.getOrdenacaoMenu()
            if self.getTipoOrdenacao() == 'des':
                contentFilter["sort_order"] = 'reverse'

            itens_menu = self.getFolderContents(contentFilter=contentFilter,batch=False)

            print >> out,'<div id="menu">'
            print >> out,'<ul id="menu1">'

            for item in itens_menu:
                item_obj = item.getObject()
                # para usuarios administradores
                link = "<li><a href='%s' target='%s'> %s</a>" % (item_obj.getLinkLocation(),item_obj.getDestinoLink(), item_obj.Title())
                if item_obj.getModoVisualizacao() == 'adm' and 'Administrators' in grupos:
                    print >> out,link
                elif item_obj.getModoVisualizacao() == 'pub':
                    print >> out,link
                else:
                    # se o usuario nao pode ver o menu pai nao poderá ver os filhos
                    continue
                sub_itens = item_obj.getFolderContents(contentFilter=contentFilter,batch=False)
                if sub_itens:
                    print >> out, "<ul>"
                    for sub_item in sub_itens:
                        sub_item_obj = sub_item.getObject()
                        link_filho = "<li><a href='%s' target='%s'> %s</a></li>" % (sub_item_obj.getLinkLocation(),sub_item_obj.getDestinoLink(), sub_item_obj.Title())
                        if sub_item.getModoVisualizacao() == 'adm' and 'Administrators' in grupos:
                            print >> out,link_filho
                        if sub_item.getModoVisualizacao() == 'pub':
                            print >> out,link_filho

                    print >> out, "</ul>"
                print >> out,'</li>'

            #Item de menu de administração do proprio menu
            if 'Administrators' in grupos:
                print >> out, "<li><a href='%s/folder_contents'>Administrar conteúdo</a></li>" % portal_url
                print >> out, "<li><a href='%s/tool_menu/view'>Administrar menus</a></li>" % portal_url
                print >> out, "<li><a href='%s/plone_control_panel'>Administrar portal</a></li>" % portal_url
            print >> out,'</ul>'
            print >> out,"</div>"

            return out.getvalue()

        except:
            out = StringIO()
            # se acontecer alguma exceção colocar apenas o menu administração
            print >> out,'<div id="menu">'
            print >> out,'<ul id="menu1">'
            print >> out, "<li><a href='%s/folder_contents'>Administrar conteúdo</a></li>" % portal_url
            print >> out, "<li><a href='%s/tool_menu/view'>Administrar menus</a></li>" % portal_url
            print >> out, "<li><a href='%s/plone_control_panel'>Administrar portal</a></li>" % portal_url
            print >> out,'</ul>'
            print >> out,"</div>"
            return out.getvalue()


    # Methods


registerType(PMenuTool, PROJECTNAME)
# end of class PMenuTool

##code-section module-footer #fill in your manual code here
##/code-section module-footer



